<template>
	<view class="main">
		<u-search height="80" placeholder="请输入搜素地址" searchIconSize="32" searchIcon="arrow-left" class="search-box"
			v-model="searchKey" :showAction="false" :animation="true" @clickIcon="back" @change="searchChange" />
		<view class="ul">
			<view class="li" v-for="item in searchList" :key="item.id" @click="goSearch(item)">
				{{item.name}}
			</view>
		</view>

		<view class="mapcell">
			<map id="popMap" :latitude="latitude" :longitude="longitude" :scale="16" :controls="controls"
				:markers="markers" />
		</view>
	</view>
</template>

<script>
	import img from '@/static/location.png'
	export default {
		data() {
			return {
				latitude: '',
				longitude: '',
				markers: [],
				controls: [],
				searchKey: '',
				searchList: [],
				title: ''
			}
		},
		onLoad(e) {
			this.title = e.title
		},
		mounted() {
			this.getLocation()
			this.addMapEvent()
		},
		methods: {
			// 点击刷新方法
			refresh(e) {
				this.getlocation();
			},
			getLocation() {
				var that = this
				// H5
				uni.getLocation({
					type: 'gcj02', // 高德地图定位需要使用 gcj02 坐标系
					success: (res) => {
						let location = `${res.longitude},${res.latitude}`
						that.longitude = res.longitude
						that.latitude = res.latitude
						let output = 'JSON'
						let key = '8187d1c02d1ba1cd0e808bce16674652'
						uni.request({
							url: `https://restapi.amap.com/v3/geocode/regeo?output=${output}&location=${location}&key=${key}&extensions=all`,
							method: 'get',
							success: (res) => { //具体捕获请看自己接口返回的形式
								if (res.data.info === 'OK') {
									let address = res.data.regeocode.formatted_address
									console.log('调接口', address);
									uni.setStorageSync('formatted_address', address)
								}

							},
							fail(error) {
								console.log(error);
							},
							complete() {

							}
						});
						// this.locationInfo = `经度: ${res.longitude}, 纬度: ${res.latitude}`;
					},
					fail: (err) => {
						console.error('定位失败', err);
					}
				});
				// #ifdef APP-PLUS
				uni.getLocation({
					type: 'gcj02',
					geocode: 'true',
					success: function(res) {
						that.latitude = res.latitude
						that.longitude = res.longitude

						// 创建地图坐标对象
						var point = new plus.maps.Point(res.longitude, res.latitude);
						//静态方法，反向地理编码
						plus.maps.Map.reverseGeocode(point, {}, (event) => {
							var address = event.address; // 转换后的地理位置
							that.locationaddress = address // 重新赋值
							console.log(that.locationaddress, 'wwh');
							// that.searchKey = that.locationaddress
							// that.searchChange()
						}, function(e) {
							console.log("失败回调", e);
						});
						// 赋值经纬度,从而得到当前位置
						that.latitude = res.latitude
						that.longitude = res.longitude

						// 地图上显示所在图标开始
						let arr = [{
							id: 0,
							longitude: res.longitude,
							latitude: res.latitude,
							name: "所在位置"
						}]
						let markers = []
						for (var i = 0; i < arr.length; i++) {
							markers = markers.concat({
								id: arr[i].id,
								latitude: arr[i].latitude, //纬度
								longitude: arr[i].longitude, //经度
								callout: { //自定义标记点上方的气泡窗口 点击有效
									content: arr[i].name, //文本
									color: '#ffffff', //文字颜色
									fontSize: 18, //文本大小
									borderRadius: 8, //边框圆角
									bgColor: 'red', //背景颜色
									display: 'ALWAYS', //常显
								},
								iconPath: '/static/location.png',
								width: 24,
								height: 24
							})
						}
						that.markers = markers // markers就是地图选点一样的功能,显示小坐标
						console.log(markers, 'www');
						// 地图上显示所在图标结束
						that.controls = [{
							id: 0,
							position: { //控件在地图的位置
								left: 15,
								top: 15,
								width: 24,
								height: 24
							},
							// iconPath: '/static/location.png'
						}]
					},
					// 定位失败
					fail: function(error) {
						uni.showModal({
							title: '提示',
							content: '获取定位失败，是否授权打开定位',
							success: (res) => {
								if (res.confirm) {
									uni.getSystemInfo({
										success: (sys) => {
											if (sys.platform == 'ios') {
												plus.runtime.openURL(
													"app-settings://");
											} else {
												var main = plus.android
													.runtimeMainActivity();
												var Intent = plus.android.importClass(
													"android.content.Intent"
												);
												var mIntent =
													new Intent(
														'android.settings.LOCATION_SOURCE_SETTINGS'
													);
												main.startActivity(mIntent);
											}
										}
									})
								}
							}
						})
					}
				})
				// #endif
			},
			back() {
				uni.setStorageSync('lng', this.longitude)
				uni.setStorageSync('lat', this.latitude)
				let {
					title
				} = this
				if(title) {
					uni.redirectTo({
						url: `/subPage1/socialized-service/farm-service/normalUser/set-arable/set-arable?title=${title}&map=map`
					})
				} else {
					this.$emit('changeStatus')
				}
			},
			addMapEvent() {
				let that = this;
				var maps = uni.createMapContext("popMap", this).$getAppMap();
				maps.onclick = function(point) {
					that.longitude = point.longitude
					that.latitude = point.latitude
					let location = `${point.longitude},${point.latitude}`
					console.log(location, 'addmapevent');
					let output = 'JSON'
					let key = '8187d1c02d1ba1cd0e808bce16674652'
					// 逆地理编码
					uni.request({
						url: `https://restapi.amap.com/v3/geocode/regeo?parameters?output=${output}&location=${location}&key=${key}`,
						method: 'get',
						success: (res) => { //具体捕获请看自己接口返回的形式
							if (res.data.status === '1') {
								let address = res.data.regeocode.formatted_address
								uni.setStorageSync('formatted_address', address)
								that.searchKey = address
								// that.searchChange()
							}

						},
						fail(error) {
							console.log(error);
						},
						complete() {

						}
					});

					console.log(that.latitude, '所选位置');

					that.markers = that.markers.filter(el => el.id === 0)
					that.markers.push({
						id: 1,
						latitude: point.latitude, //纬度
						longitude: point.longitude, //经度
						callout: { //自定义标记点上方的气泡窗口 点击有效
							content: '所选位置', //文本
							color: '#ffffff', //文字颜色
							fontSize: 18, //文本大小
							borderRadius: 8, //边框圆角
							bgColor: 'red', //背景颜色
							display: 'ALWAYS', //常显
						},
						iconPath: '/static/location.png',
						width: 24,
						height: 24
					})
					let pages = getCurrentPages()
					let prevPage = pages[pages.length - 2]
					let currentLocat = that.longitude + ',' + that.latitude
					prevPage.$vm.getMapValue(currentLocat)
					setTimeout(res => {
						uni.navigateBack({
							delta: 1 // 返回的页面数
						})
					}, 1000)
				}
			},
			searchChange() {
				if (this.searchKey === '') {
					if (e === '') {
						this.searchList = []
						return
					}
				}
				let output = 'JSON'
				let key = '8187d1c02d1ba1cd0e808bce16674652'
				uni.request({
					url: `https://restapi.amap.com/v3/place/text?parameters?output=${output}&key=${key}&keywords=${this.searchKey}`,
					method: 'get',
					success: (res) => { //具体捕获请看自己接口返回的形式
						if (res.data.status === '1') {
							this.searchList = res.data.pois
							console.log(this.searchList, '搜索');
						}

					},
					fail(error) {
						console.log(error);
					},
					complete() {

					}
				});
			},
			goSearch(item) {
				console.log(item);
				let location = item.location.split(',')
				this.longitude = location[0]
				this.latitude = location[1]
				let address = `${item.pname}${item.cityname}${item.adname}${item.name}`
				uni.setStorageSync('formatted_address', address)

				this.back()
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		position: relative;
	}

	.mapcell {
		margin-top: 180rpx;
		width: 100%;
		height: calc(100vh - 180rpx);

		map {
			width: 100%;
			height: 100% !important;
		}
	}

	/deep/ .uni-navbar {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 999;
		// pointer-events: none;
	}

	/deep/.uni-navbar__content,
	/deep/.uni-navbar__header {
		border-bottom: none !important;
	}

	.search-box {
		width: 100%;
		position: fixed;
		top: 20rpx;
		left: 50%;
		transform: translateY(50%) translateX(-50%);
		border: 2rpx solid #ccc;
		border-radius: 60rpx;
		z-index: 9999;
	}

	.ul {
		position: relative;
		width: 100%;
		padding: 0 20rpx;
		background-color: #fff;
		max-height: 300rpx;
		top: 160rpx;
		z-index: 99999;
		overflow-y: auto;

		.li {
			margin-bottom: 10rpx;
		}

	}

	::v-deep #popMap {
		z-index: 1 !important;
	}
</style>